class Writer(object):
    def __init__(self):
        pass
    def write(self):
        pass


from SkipList import SkipList
from LogNumber import LogNumber
class MemTable(object):
    class WriterImp(Writer):
        Level0Name = "level"
        def __init__(self, skipList):
            self.__logNumber = LogNumber()
            self.__skipList = skipList
            self.__file = None

        def __fileName(self):
            return "%s-0-%d.lvl" % (MemTable.WriterImp.Level0Name, self.__logNumber.next())

        def write(self):
            if self.__skipList is None:
                return 

            self.__file = open(self.__fileName(), "a")
            it = self.__skipList.iterator()
            while it.hasNext():
                #print("write to [%s]: %s" % (self.__fileName(), str(it.next())) ) 
                self.__file.write(str(it.next()) + "\n")
            #end while
            self.__file.close()
        #end def

    def __init__(self):
        self.__sl = SkipList(10)

    def size(self):
        return self.__sl.size()
    def get(self, key):
        return self.__sl.get(key)

    #ret : 1 -> replaced; 0 -> insert
    def put(self, key, val):
        return self.__sl.put(key, val)

    #delete None -> notExist; NotNone -> deleted 
    def delete(self, key):
        return self.__sl.delete(key)

    def getWriter(self):
        return MemTable.WriterImp(self.__sl)


import unittest
class TestMemTable(unittest.TestCase):
    def test(self):
        mem = MemTable()
        self.assertEqual(0, mem.size())

        self.assertEqual(0, mem.put("hello0", "world0"))
        self.assertIsNotNone(mem.get("hello0"))
        self.assertEqual(1, mem.size())

        self.assertEqual(0, mem.put("hello1", "world1"))
        self.assertIsNotNone(mem.get("hello1"))

        self.assertEqual(0, mem.put("hello2", "world2"))
        self.assertIsNotNone(mem.get("hello2"))

        self.assertEqual(0, mem.put("hello3", "world3"))
        self.assertIsNotNone(mem.get("hello3"))

        self.assertEqual(0, mem.put("hello4", "world4"))
        self.assertIsNotNone(mem.get("hello4"))
        self.assertEqual(5, mem.size())

        mem.getWriter().write()

if __name__ == "__main__":
    suite = unittest.TestSuite([
        unittest.TestLoader().loadTestsFromTestCase(TestMemTable), 
    ])
    unittest.TextTestRunner(verbosity=2).run(suite)
